package com.fow.core.platform.sms.impl;

import com.fow.core.platform.sms.SMSService;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URLEncoder;

/**
 * Created by Greg.Chen on 14-11-12.
 */
public class YiChiSMSServiceImpl implements SMSService {
    private static Logger logger = LoggerFactory.getLogger(YiChiSMSServiceImpl.class);

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getSuser() {
        return suser;
    }

    public void setSuser(String suser) {
        this.suser = suser;
    }

    public String getSpass() {
        return spass;
    }

    public void setSpass(String spass) {
        this.spass = spass;
    }

    private String domain;
    private String uri;
    private String suser;
    private String spass;

    @Override
    public void sendCaptcha(String phone, String captcha, String signature) throws IOException {

        String uri = this.domain + this.uri +"suser="+ this.suser+"&spass="+ this.spass+"&telnum="+ phone +"&nr="
                + URLEncoder.encode(String.format("您的验证码为：%s【%s】", captcha, signature), "gb2312");
        logger.debug("uri: "+uri);

        send(uri);
    }

    @Override
    public void send(String phone, String message, String signature) throws IOException {

        String uri = this.domain + this.uri +"suser="+ this.suser+"&spass="+ this.spass+"&telnum="+ phone +"&nr="
                + URLEncoder.encode(String.format("%s【%s】", message, signature), "gb2312");
        logger.debug("uri: "+uri);

        send(uri);
    }

    private void send(String uri) throws IOException {
        HttpClient client = new DefaultHttpClient();
        HttpRequestBase request = new HttpGet(uri);

        HttpResponse response = client.execute(request);
        int responseCode = response.getStatusLine().getStatusCode();
        logger.debug("responseCode: " + responseCode);
        byte[] content = EntityUtils.toByteArray(response.getEntity());

        logger.debug("result: " + new String(content));
        request.releaseConnection();
    }

    /**
     * 6位随机数
     * @return
     */
    @Override
    public String getCaptcha() {
        String captcha = "";
        for(int i=0;i<6;i++)
        {
            captcha +=(int)(Math.random()*10);
        }
        return captcha;
    }
}
